package ro.fortech.workshop_demo.access.webservice;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.AndroidHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import ro.fortech.workshop_demo.utils.Utils;

/**
 * Base manager responsible for ws calls. Contains the basic rest call methods
 * implementation: get, post, put, delete. This class will be subclassed by
 * specific managers for each API.
 *
 * @author florinv
 */
public class WebServiceManager {
    /**
     * Timeout until a connection is established
     */
    private static final int TIMEOUT_CONNECTION = 30000;
    /**
     * The default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
     */
    private static final int TIMEOUT_SOCKET = 30000;
    /**
     * User agent name used when creating the AndroidHttpClient
     */
    public static final String USER_AGENT_NAME = "android";
    /**
     * Http client used by manager to connect
     */
    private AndroidHttpClient httpClient;
    /**
     * Private constructor
     */
    protected WebServiceManager() {
        if (httpClient == null) {
            HttpParams params = new BasicHttpParams();
            // Add timeout
            HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);
            httpClient = AndroidHttpClient.newInstance(USER_AGENT_NAME);
        }
    }

    /**
     * Executes a get request
     *
     * @param url           : url of the request
     * @param handler       : response handler and parser
     */
    protected void getRequest(String url, final JSONParser handler) {
        final HttpGet getMethod = new HttpGet(url);
        try {
            Thread background = new Thread(new Runnable() {

                public void run() {
                    try {
                        httpClient.execute(getMethod, handler);
                    } catch (Exception e) {
                        e.printStackTrace();
                        handler.connectionFailed();
                    }
                }
            });
            background.start();
        } catch (Throwable e) {
            e.printStackTrace();
            handler.connectionFailed();
        }
    }
}
